﻿using SuperMap.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MDF
{
    /// <summary>
    /// 数据融合类
    /// </summary>
    class DataFusion
    {
        private int[] m_modeFusion;
        private bool m_IsSelections;
        private string[] m_selectinosNames;

        private Datasources m_datasources;
        private DatasetVector[] m_SetToSet;
        private DatasetsMatchResult m_matchResult;
        /// <summary>
        /// 数据融合初始化
        /// </summary>
        /// <param name="datasources">数据源集合</param>
        public DataFusion(Datasources datasources)
        {
            m_datasources = datasources;
        }
        /// <summary>
        /// 执行数据匹配
        /// </summary>
        /// <param name="modeFusion">数据融合的模式</param>
        /// <param name="matchResult">保存结果的结果类</param>
        /// <param name="SetToSet">要计算的数据集对</param>
        /// <param name="IsSelections">是否为选择集</param>
        /// <param name="selectinosNames">选择集的名称</param>
        /// <param name="Token">取消操作的对象</param>
        public void RunDataMatch(int[] modeFusion, DatasetsMatchResult matchResult, DatasetVector[] SetToSet, bool IsSelections, string[] selectinosNames, CancellationToken Token)
        {
            try
            {
                //获取值
                m_SetToSet = SetToSet;
                m_modeFusion = modeFusion;
                m_matchResult = matchResult;
                m_IsSelections = IsSelections;
                m_selectinosNames = selectinosNames;
                //顺序执行匹配模式，已执行过则不在执行
                List<Task> tasks = new List<Task>();
                foreach (int mode in m_modeFusion)
                {
                    switch (mode)
                    {
                        case 1:
                            //执行空间匹配
                            if (m_matchResult.MatchSpaceResult == null)
                            {
                                tasks.Add(new Task(() => RunMatchingSpace(Token), Token));
                            }
                            else
                            {
                                DatasetsMatchResult.SpaceProgressValue = 100;
                            }
                            break;
                        case 2:
                            //执行属性匹配
                            if (m_matchResult.MatchAttributeResult == null)
                            {
                                tasks.Add(new Task(() => RunMatchingAttribute(Token), Token));
                            }
                            else
                            {
                                DatasetsMatchResult.AttributeProgressValue = 100;
                            }
                            break;
                        case 3:
                            //执行拓扑匹配
                            if (m_matchResult.MatchTopologyResult == null)
                            {
                                tasks.Add(new Task(() => RunMatchingTopology(Token), Token));
                            }
                            else
                            {
                                DatasetsMatchResult.TopollogyProgressValue = 100;
                            }
                            break;
                        default:
                            break;
                    }
                }
                for (int i = 0; i < tasks.Count; i++)
                {
                    tasks[i].Start();
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 执行空间匹配
        /// </summary>
        /// <param name="Token">取消操作的对象</param>
        private void RunMatchingSpace(CancellationToken Token)
        {
            try
            {
                //实例化执行几何匹配的对象
                MatchSpace matchSpace = new MatchSpace(false);
                //获取数据集相关阈值信息
                double[] yuzhi = GetYuZhi(m_SetToSet[0].Name, m_SetToSet[1].Name, "..", new string[] { "DistanceThershold", "LengthThershold" }, false);
                if (yuzhi.Length != 0)
                {
                    if (m_SetToSet[0].Type == DatasetType.Point)
                    {
                        //保存结果
                        List<double[]> matchSpaceResult;
                        if (m_IsSelections)
                        {
                            //获取id数组
                            int[] set1IDs = GetSelectionDataIDs(m_selectinosNames[0], m_SetToSet[0].Name);
                            int[] set2IDs = GetSelectionDataIDs(m_selectinosNames[1], m_SetToSet[1].Name);
                            //获取点记录集
                            Recordset point1 = m_SetToSet[0].Query(set1IDs, CursorType.Static);
                            Recordset point2 = m_SetToSet[1].Query(set2IDs, CursorType.Static);
                            //进行几何匹配
                            matchSpaceResult = matchSpace.MatchDataPoint1(point1, point2, yuzhi[0], m_SetToSet[0].PrjCoordSys.CoordUnit, Token);
                            //释放记录集
                            point1.Dispose();
                            point2.Dispose();
                        }
                        else
                        {
                            //获取点记录集
                            Recordset point1 = m_SetToSet[0].GetRecordset(false, CursorType.Static);
                            Recordset point2 = m_SetToSet[1].GetRecordset(false, CursorType.Static);
                            //进行几何匹配
                            matchSpaceResult = matchSpace.MatchDataPoint1(point1, point2, yuzhi[0], m_SetToSet[0].PrjCoordSys.CoordUnit, Token);
                            //释放记录集
                            point1.Dispose();
                            point2.Dispose();
                        }
                        if (matchSpaceResult != null)
                        {
                            //保存对应匹配集的结果信息
                            m_matchResult.MatchSpaceResult = matchSpaceResult;
                        }
                    }
                    else if (m_SetToSet[0].Type == DatasetType.Line)
                    {
                        //保存结果
                        List<double[]> matchSpaceResult;
                        if (m_IsSelections)
                        {
                            //获取id数组
                            int[] set1IDs = GetSelectionDataIDs(m_selectinosNames[0], m_SetToSet[0].Name);
                            int[] set2IDs = GetSelectionDataIDs(m_selectinosNames[1], m_SetToSet[1].Name);
                            //获取线记录集
                            Recordset line1 = m_SetToSet[0].Query(set1IDs, CursorType.Static);
                            Recordset line2 = m_SetToSet[1].Query(set2IDs, CursorType.Static);
                            //进行几何匹配
                            matchSpaceResult = matchSpace.MatchDataLine(line1, line2, yuzhi[0], yuzhi[1], m_SetToSet[0].PrjCoordSys.CoordUnit, Token);
                            //释放记录集
                            line1.Dispose();
                            line1.Dispose();
                        }
                        else
                        {
                            //获取线记录集
                            Recordset line1 = m_SetToSet[0].GetRecordset(false, CursorType.Static);
                            Recordset line2 = m_SetToSet[1].GetRecordset(false, CursorType.Static);
                            //进行几何匹配
                            matchSpaceResult = matchSpace.MatchDataLine(line1, line2, yuzhi[0], yuzhi[1], m_SetToSet[0].PrjCoordSys.CoordUnit, Token);
                            //释放记录集
                            line1.Dispose();
                            line1.Dispose();
                        }
                        if (matchSpaceResult != null)
                        {
                            //保存对应匹配集的结果信息
                            m_matchResult.MatchSpaceResult = matchSpaceResult;
                        }
                    }
                    else
                    {
                        MessageBox.Show("格式内容似乎出了点问题，无法计算~\n当前仅支持二维点、线计算。", "警告：");
                    }
                }
                else
                {
                    MessageBox.Show("数据集未设置阈值：" + m_SetToSet[0].Name + ":" + m_SetToSet[1].Name, "警告：");
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 执行属性匹配
        /// </summary>
        /// <param name="Token">取消操作的对象</param>
        private void RunMatchingAttribute(CancellationToken Token)
        {
            try
            {
                //实例化属性匹配对象
                MatchAttribute matchAttribute = new MatchAttribute(false);
                //获取数据集映射信息
                List<string[]> fieldInfos = new List<string[]>();
                IO_xml pp_xml = new IO_xml("ShuXingPiPei");
                List<string[]> strs = pp_xml.ReadChildValues(m_SetToSet[0].Name + ".." + m_SetToSet[1].Name);
                foreach (string[] str in strs)
                {
                    fieldInfos.Add(new string[] { str[1], str[2] });
                }
                //获取同义词集
                IO_xml zd_xml = new IO_xml("ShuXingZiDian");
                List<string[]> sameSets = new List<string[]>();
                string[] sameSetNames = zd_xml.ReadChildNodesName("SynSet");
                foreach (string name in sameSetNames)
                {
                    sameSets.Add(zd_xml.ReadInnerText(name).Split('_'));
                }
                if (fieldInfos.Count != 0)
                {
                    //保存结果
                    List<double[]> matchAttributeResult;
                    if (m_IsSelections)
                    {
                        //获取id数组
                        int[] set1IDs = GetSelectionDataIDs(m_selectinosNames[0], m_SetToSet[0].Name);
                        int[] set2IDs = GetSelectionDataIDs(m_selectinosNames[1], m_SetToSet[1].Name);
                        //获取记录集
                        Recordset reSet1 = m_SetToSet[0].Query(set1IDs, CursorType.Static);
                        Recordset reSet2 = m_SetToSet[1].Query(set2IDs, CursorType.Static);
                        //进行属性匹配
                        matchAttributeResult = matchAttribute.MatchDataset(reSet1, reSet2, fieldInfos, sameSets, Token);
                        //释放记录集
                        reSet1.Dispose();
                        reSet1.Dispose();
                    }
                    else
                    {
                        //获取记录集
                        Recordset reSet1 = m_SetToSet[0].GetRecordset(false, CursorType.Static);
                        Recordset reSet2 = m_SetToSet[1].GetRecordset(false, CursorType.Static);
                        //进行属性匹配
                        matchAttributeResult = matchAttribute.MatchDataset(reSet1, reSet2, fieldInfos, sameSets, Token);
                        //释放记录集
                        reSet1.Dispose();
                        reSet1.Dispose();
                    }
                    if (matchAttributeResult != null)
                    {
                        //保存对应匹配集的结果信息
                        m_matchResult.MatchAttributeResult = matchAttributeResult;
                        m_matchResult.MatchAttributeFieldResult = matchAttribute.FieldResult;
                    }

                }
                else
                {
                    MessageBox.Show("数据集未设置阈值：" + m_SetToSet[0].Name + ":" + m_SetToSet[1].Name, "警告：");
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 执行拓扑匹配
        /// </summary>
        /// <param name="Token">取消操作的对象</param>
        private void RunMatchingTopology(CancellationToken Token)
        {
            try
            {
                //实例化拓扑匹配对象(默认用第一个数据源)
                MatchTopology matchTopology = new MatchTopology(m_datasources[0],false);
                //获取数据集相关阈值信息
                double[] yuzhi = GetYuZhi(m_SetToSet[0].Name, m_SetToSet[1].Name, "...", new string[] { "ErrorThershold", "ToleranceThershold", "DepthThershold" }, true);
                if (yuzhi.Length != 0)
                {
                    if (m_SetToSet[0].Type == DatasetType.Point)
                    {
                        //保存结果
                        List<double[]> matchTopologyResult;
                        if (m_IsSelections)
                        {
                            //获取id数组
                            int[] set1IDs = GetSelectionDataIDs(m_selectinosNames[0], m_SetToSet[0].Name);
                            int[] set2IDs = GetSelectionDataIDs(m_selectinosNames[1], m_SetToSet[1].Name);
                            //获取点记录集
                            Recordset point1 = m_SetToSet[0].Query(set1IDs, CursorType.Static);
                            Recordset point2 = m_SetToSet[1].Query(set2IDs, CursorType.Static);
                            //获取点记录集所需要的线数据集
                            DatasetVector[] linkLines1 = GetLinkDatasets(point1.Dataset.Name);
                            DatasetVector[] linkLines2 = GetLinkDatasets(point2.Dataset.Name);
                            //进行拓扑匹配
                            matchTopologyResult = matchTopology.MatchDataPoint(point1, linkLines1, point2, linkLines2, yuzhi[0], yuzhi[1], (int)yuzhi[2], Token);
                            //释放记录集
                            point1.Dispose();
                            point2.Dispose();
                        }
                        else
                        {
                            //获取点记录集
                            Recordset point1 = m_SetToSet[0].GetRecordset(false, CursorType.Static);
                            Recordset point2 = m_SetToSet[1].GetRecordset(false, CursorType.Static);
                            //获取点记录集所需要的线数据集
                            DatasetVector[] linkLines1 = GetLinkDatasets(point1.Dataset.Name);
                            DatasetVector[] linkLines2 = GetLinkDatasets(point2.Dataset.Name);
                            //进行拓扑匹配
                            matchTopologyResult = matchTopology.MatchDataPoint(point1, linkLines1, point2, linkLines2, yuzhi[0], yuzhi[1], (int)yuzhi[2], Token);
                            //释放记录集
                            point1.Dispose();
                            point2.Dispose();
                        }
                        if (matchTopologyResult != null)
                        {
                            //保存对应匹配集的结果信息
                            m_matchResult.MatchTopologyResult = matchTopologyResult;
                        }
                    }
                    else if (m_SetToSet[0].Type == DatasetType.Line)
                    {
                        //保存结果
                        List<double[]> matchTopologyResult;
                        if (m_IsSelections)
                        {
                            //获取id数组
                            int[] set1IDs = GetSelectionDataIDs(m_selectinosNames[0], m_SetToSet[0].Name);
                            int[] set2IDs = GetSelectionDataIDs(m_selectinosNames[1], m_SetToSet[1].Name);
                            //获取线记录集
                            Recordset line1 = m_SetToSet[0].Query(set1IDs, CursorType.Static);
                            Recordset line2 = m_SetToSet[1].Query(set2IDs, CursorType.Static);
                            //进行几何匹配
                            matchTopologyResult = matchTopology.MatchDataLine(line1, line2, yuzhi[0], yuzhi[1], (int)yuzhi[2], Token);
                            //释放记录集
                            line1.Dispose();
                            line1.Dispose();
                        }
                        else
                        {
                            //获取线记录集
                            Recordset line1 = m_SetToSet[0].GetRecordset(false, CursorType.Static);
                            Recordset line2 = m_SetToSet[1].GetRecordset(false, CursorType.Static);
                            //进行几何匹配
                            matchTopologyResult = matchTopology.MatchDataLine(line1, line2, yuzhi[0], yuzhi[1], (int)yuzhi[2], Token);
                            //释放记录集
                            line1.Dispose();
                            line1.Dispose();
                        }
                        if (matchTopologyResult != null)
                        {
                            //保存对应匹配集的结果信息
                            m_matchResult.MatchTopologyResult = matchTopologyResult;
                        }
                    }
                    else
                    {
                        MessageBox.Show("格式内容似乎出了点问题，无法计算~\n当前仅支持二维点、线计算。", "警告：");
                    }
                }
                else
                {
                    MessageBox.Show("数据集未设置阈值：" + m_SetToSet[0].Name + ":" + m_SetToSet[1].Name, "警告：");
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 获取阈值信息
        /// </summary>
        /// <param name="set1Name">数据集1的名字</param>
        /// <param name="set2Name">数据集2的名字</param>
        /// <param name="m_andStr">连接字符串</param>
        /// <param name="m_keys">属性值关键字集合</param>
        /// <param name="IsTopology">是否为获取拓扑阈值，true获取拓扑阈值，false获取空间阈值</param>
        /// <returns>返回阈值集合</returns>
        private double[] GetYuZhi(string set1Name, string set2Name,string m_andStr,string[] m_keys,bool IsTopology)
        {
            try
            {
                //实例化xml读写对象
                IO_xml m_Xml = new IO_xml("PiPeiYuZhi");
                //数据节点名称为两个数据的名称
                string dataName = set1Name + m_andStr + set2Name;
                string dataNameRe = set2Name + m_andStr + set1Name;
                //判断信息是否存在
                if (m_Xml.ReadValueByKey(dataName, m_keys[0]) != null)
                {
                    List<double> yuzhi = new List<double>();
                    double value1 = double.Parse(m_Xml.ReadValueByKey(dataName, m_keys[0]));
                    double value2 = double.Parse(m_Xml.ReadValueByKey(dataName, m_keys[1]));
                    yuzhi.Add(value1);
                    yuzhi.Add(value2);
                    if (IsTopology)
                    {
                        double value3 = double.Parse(m_Xml.ReadValueByKey(dataName, m_keys[2]));
                        yuzhi.Add(value3);
                    }

                    return yuzhi.ToArray();
                }
                else if (m_Xml.ReadValueByKey(dataNameRe, m_keys[0]) != null)
                {
                    List<double> yuzhi = new List<double>();
                    double value1 = double.Parse(m_Xml.ReadValueByKey(dataNameRe, m_keys[0]));
                    double value2 = double.Parse(m_Xml.ReadValueByKey(dataNameRe, m_keys[1]));
                    yuzhi.Add(value1);
                    yuzhi.Add(value2);
                    if (IsTopology)
                    {
                        double value3 = double.Parse(m_Xml.ReadValueByKey(dataNameRe, m_keys[2]));
                        yuzhi.Add(value3);
                    }

                    return yuzhi.ToArray();
                }
                else
                {
                    return new double[] { };
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 获取选择集中的数据集信息
        /// </summary>
        /// <param name="selectionsName">选择集的名字</param>
        /// <param name="datasetName">数据集的名字</param>
        /// <returns>返回id数组</returns>
        private int[] GetSelectionDataIDs(string selectionsName, string datasetName)
        {
            try
            {
                //实例化xml读写对象
                IO_xml m_Xml = new IO_xml("SelectionData");
                //获取ids文本
                string idsText = m_Xml.ReadInnerText(selectionsName, datasetName);
                string[] idsStr = idsText.Remove(0, 1).Split('_');
                int[] IDs = Array.ConvertAll(idsStr, int.Parse);
                //返回结果
                return IDs;
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 获取点数据链接的线数据集合
        /// </summary>
        /// <param name="datasetName">点数据集名称</param>
        /// <returns>返回点线数据集合</returns>
        private DatasetVector[] GetLinkDatasets(string datasetName)
        {
            try
            {
                //实例化xml读写对象
                IO_xml m_Xml = new IO_xml("PiPeiYuZhi");
                //获取数据集信息（不建议有同名数据集存在）
                string[] linesetNames = m_Xml.ReadValues("TuoPuLink", datasetName);
                List<DatasetVector> datasetVector = new List<DatasetVector>();
                foreach (string linesetName in linesetNames)
                {
                    foreach (Datasource datasource in m_datasources)
                    {
                        if (datasource.Datasets.Contains(linesetName))
                        {
                            //获取数据后跳出
                            datasetVector.Add(datasource.Datasets[linesetName] as DatasetVector);
                            break;
                        }
                    }
                }
                return datasetVector.ToArray();
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 执行数据融合
        /// </summary>
        /// <param name="dataSourceName">数据源的名称</param>
        /// <param name="datasetName">保存数据集的名字</param>
        /// <param name="Weights">权重值{空间、属性、拓扑}</param>
        public void RunDataFusion(string dataSourceName,string datasetName, double[] Weights)
        {
            try
            {
                //以第一数据集的记录集,新建一个保存数据集，并补全字段
                Recordset recordset1 = m_SetToSet[0].GetRecordset(false, CursorType.Static);
                Recordset recordset2 = m_SetToSet[1].GetRecordset(false, CursorType.Static);
                //检查名字是否合法，可直接获取合法的数据集名
                string saveSetName = m_datasources[dataSourceName].Datasets.GetAvailableDatasetName(datasetName);
                DatasetVector saveVector = m_datasources[dataSourceName].Datasets.CreateAndAppendWithSmid(saveSetName, recordset1);
                //补全数据集字段
                FieldInfos saveFieldInfos = FillFieldInfos(saveVector.FieldInfos, m_SetToSet[1].FieldInfos);
                //获取字段映射记录
                List<string> fields1 = new List<string>();
                List<string> fields2 = new List<string>();
                foreach (string[] filedName12 in m_matchResult.MatchAttributeFieldResult)
                {
                    fields1.Add(filedName12[0]);
                    fields2.Add(filedName12[1]);
                }
                //获取动态记录集
                Recordset saveRecordset = saveVector.GetRecordset(false, CursorType.Dynamic);
                //遍历整个记录集，并筛选匹配结果进行填充，批量更新每500条记录
                Recordset.BatchEditor editor = saveRecordset.Batch;
                editor.MaxRecordCount = 500;
                //开始更新
                editor.Begin();
                saveRecordset.MoveFirst();
                for (int i = 0; i < saveRecordset.RecordCount; i++)
                {
                    //获取当前记录id，并搜索匹配结果的id
                    double ID = SearchEqualID(saveRecordset.GetID(), Weights);
                    if (recordset2.SeekID((int)ID))
                    {
                        //遍历字段进行赋值
                        foreach (FieldInfo fieldInfo in saveFieldInfos)
                        {
                            //判断当前位置是否有值，有值则不赋值，无值并且非系统字段则查询数据集2的对应字段的值，并赋值
                            if (!fieldInfo.IsSystemField && saveRecordset.GetFieldValue(fieldInfo.Name) == null)
                            {
                                //判断当前字段是否有映射
                                if (fields1.Contains(fieldInfo.Name))
                                {
                                    //有映射，则查询对应字段
                                    string fieldName2 = fields2[fields1.IndexOf(fieldInfo.Name)];
                                    saveRecordset.SetFieldValue(fieldInfo.Name, recordset2.GetFieldValue(fieldName2));
                                }
                                else
                                {
                                    //无映射则直接搜索数据集2的对应字段的值
                                    saveRecordset.SetFieldValue(fieldInfo.Name, recordset2.GetFieldValue(fieldInfo.Name));
                                }
                            }
                        }
                    }
                    //移动记录
                    saveRecordset.MoveNext();
                    //记录进度
                    DatasetsMatchResult.FusionProgressCount++;
                    DatasetsMatchResult.FusionProgressValue = DatasetsMatchResult.FusionProgressCount * 100 / DatasetsMatchResult.SetsRecordCountSum;
                }
                // 批量操作统一提交
                editor.Update();
                //释放资源
                recordset1.Dispose();
                recordset2.Dispose();
                saveRecordset.Dispose();

            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 执行数据融合
        /// </summary>
        /// <param name="dataSourceName">数据源的名称</param>
        /// <param name="datasetName">保存数据集的名字</param>
        /// <param name="Weights">权重值{空间、属性、拓扑}</param>
        /// <param name="Token">取消操作的对象</param>
        public void RunDataFusion(string dataSourceName, string datasetName, double[] Weights, CancellationToken Token)
        {
            try
            {
                //以第一数据集的记录集,新建一个保存数据集，并补全字段
                Recordset recordset1 = m_SetToSet[0].GetRecordset(false, CursorType.Static);
                Recordset recordset2 = m_SetToSet[1].GetRecordset(false, CursorType.Static);
                //检查名字是否合法，可直接获取合法的数据集名
                string saveSetName = m_datasources[dataSourceName].Datasets.GetAvailableDatasetName(datasetName);
                DatasetVector saveVector = m_datasources[dataSourceName].CopyDataset(recordset1.Dataset,saveSetName,EncodeType.Int32 ) as DatasetVector;
                saveVector.IsReadOnly = false;
                //补全数据集字段
                FieldInfos saveFieldInfos = FillFieldInfos(saveVector.FieldInfos, m_SetToSet[1].FieldInfos);
                //获取字段映射记录
                List<string> fields1 = new List<string>();
                List<string> fields2 = new List<string>();
                foreach (string[] filedName12 in m_matchResult.MatchAttributeFieldResult)
                {
                    fields1.Add(filedName12[0]);
                    fields2.Add(filedName12[1]);
                }
                //获取数据集2的字段
                FieldInfos record2Fields = recordset2.GetFieldInfos();
                //获取动态记录集
                Recordset saveRecordset = saveVector.GetRecordset(false, CursorType.Dynamic);
                //遍历整个记录集，并筛选匹配结果进行填充，批量更新每500条记录
                Recordset.BatchEditor editor = saveRecordset.Batch;
                editor.MaxRecordCount = 500;
                //开始更新
                editor.Begin();
                saveRecordset.MoveFirst();
                for (int i = 0; i < saveRecordset.RecordCount; i++)
                {
                    if (Token.IsCancellationRequested)
                    {
                        // 批量操作统一提交
                        editor.Update();
                        //释放资源
                        recordset1.Dispose();
                        recordset2.Dispose();
                        saveRecordset.Dispose();
                        return;
                    }
                    else
                    {
                        //获取当前记录id，并搜索匹配结果的id
                        double ID = SearchEqualID(saveRecordset.GetID(), Weights);
                        if (recordset2.SeekID((int)ID))
                        {
                            //遍历字段进行赋值
                            foreach (FieldInfo fieldInfo in saveFieldInfos)
                            {
                                //判断当前位置是否有值，有值则不赋值，无值并且非系统字段则查询数据集2的对应字段的值，并赋值
                                if (!fieldInfo.IsSystemField && saveRecordset.GetFieldValue(fieldInfo.Name) == null)
                                {
                                    //判断当前字段是否有映射
                                    if (fields1.Contains(fieldInfo.Name))
                                    {
                                        //有映射，则查询对应字段
                                        string fieldName2 = fields2[fields1.IndexOf(fieldInfo.Name)];
                                        saveRecordset.SetFieldValue(fieldInfo.Name, recordset2.GetFieldValue(fieldName2));
                                    }
                                    else
                                    {
                                        //无映射则直接搜索数据集2的对应字段的值
                                        if (record2Fields[fieldInfo.Name] != null)
                                        {
                                            saveRecordset.SetFieldValue(fieldInfo.Name, recordset2.GetFieldValue(fieldInfo.Name));
                                        }
                                    }
                                }
                            }
                        }
                        //移动记录
                        saveRecordset.MoveNext();
                        //记录进度
                        DatasetsMatchResult.FusionProgressCount++;
                        DatasetsMatchResult.FusionProgressValue = DatasetsMatchResult.FusionProgressCount * 100 / DatasetsMatchResult.SetsRecordCountSum;
                    }
                }
                // 批量操作统一提交
                editor.Update();
                //释放资源
                recordset1.Dispose();
                recordset2.Dispose();
                saveRecordset.Dispose();

            }
            catch (Exception)
            {

                throw;
            }
        }
        private FieldInfos FillFieldInfos(FieldInfos saveFieldInfos, FieldInfos set2FieldInfos)
        {
            try
            {
                //用第二数据集补全字段未匹配字段
                //获取已匹配的字段
                List<string> exFieldinfos = new List<string>();
                if (m_matchResult.MatchAttributeFieldResult != null)
                {
                    foreach (string[] Fieldinfo12 in m_matchResult.MatchAttributeFieldResult)
                    {
                        exFieldinfos.Add(Fieldinfo12[1]);
                    }
                    //如果有完成属性匹配，则补全除系统字段外的未匹配字段
                    foreach (FieldInfo fieldInfo in set2FieldInfos)
                    {
                        if (!fieldInfo.IsSystemField && !exFieldinfos.Contains(fieldInfo.Name) && saveFieldInfos[fieldInfo.Name] == null)
                        {
                            //追加该字段
                            saveFieldInfos.Add(fieldInfo);
                        }
                    }
                }
                else
                {
                    //如果没有进行属性匹配，则保留除系统字段外的全部字段
                    foreach (FieldInfo fieldInfo in set2FieldInfos)
                    {
                        if (!fieldInfo.IsSystemField)
                        {
                            //判断是否存在同名字段
                            if (saveFieldInfos[fieldInfo.Name] == null)
                            {
                                //不存在，直接追加该字段
                                saveFieldInfos.Add(fieldInfo);
                            }
                            else
                            {
                                //存在，则更新名字再追加
                                FieldInfo newfieldInfo = fieldInfo.Clone();
                                newfieldInfo.Name = fieldInfo.Name + "_2";
                                saveFieldInfos.Add(newfieldInfo);
                                //添加名字映射记录
                                m_matchResult.MatchAttributeFieldResult.Add(new string[] { fieldInfo.Name, newfieldInfo.Name });
                            }
                        }
                    }
                }
                return saveFieldInfos;
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 计算相似度最大的数据，并返回id
        /// </summary>
        /// <param name="ID">当前数据的id</param>
        /// <param name="Weights">权重值{空间、属性、拓扑}</param>
        /// <returns>返回id值，double型，获取异常时返回 -1.0</returns>
        private double SearchEqualID(int ID, double[] Weights)
        {
            try
            {
                //只返回最佳匹配的id值，先筛选最合适的值
                List<double> IDs = new List<double>();
                List<double> Values = new List<double>();
                for (int n = 0; n < m_modeFusion.Length; n++)
                {
                    switch (m_modeFusion[n])
                    {
                        case 1:
                            //查询空间匹配(由于距离阈值，能匹配的id值一般不多，可以全部保留)
                            if (IDs.Count > 0)
                            {
                                for (int i = 0; i < m_matchResult.MatchSpaceResult.Count; i++)
                                {
                                    //当第二数据的id值已经包含在IDs数组中时，才获取相似度值
                                    if (m_matchResult.MatchSpaceResult[i][0] == ID && IDs.Contains(m_matchResult.MatchSpaceResult[i][1]))
                                    {
                                        //记录下当前匹配的相似度值
                                        int index = IDs.IndexOf(m_matchResult.MatchSpaceResult[i][1]);
                                        Values[index] += m_matchResult.MatchSpaceResult[i][2] * Weights[n];
                                    }
                                }
                            }
                            else
                            {
                                for (int i = 0; i < m_matchResult.MatchSpaceResult.Count; i++)
                                {
                                    if (m_matchResult.MatchSpaceResult[i][0] == ID)
                                    {
                                        //记录下与当前ID值匹配的第二数据集的id和相似度值*权值
                                        IDs.Add(m_matchResult.MatchSpaceResult[i][1]);
                                        Values.Add(m_matchResult.MatchSpaceResult[i][2] * Weights[n]);
                                    }
                                }
                            }
                            break;
                        case 2:
                            //查询属性匹配(全部匹配，通常产生较多结果，因此只保留相似度最大的五项结果)
                            if (IDs.Count > 0)
                            {
                                for (int i = 0; i < m_matchResult.MatchAttributeResult.Count; i++)
                                {
                                    //当第二数据的id值已经包含在IDs数组中时，才获取相似度值
                                    if (m_matchResult.MatchAttributeResult[i][0] == ID && IDs.Contains(m_matchResult.MatchAttributeResult[i][1]))
                                    {
                                        //记录下当前匹配的相似度值
                                        int index = IDs.IndexOf(m_matchResult.MatchAttributeResult[i][1]);
                                        Values[index] += m_matchResult.MatchAttributeResult[i][2] * Weights[1];
                                    }
                                }
                            }
                            else
                            {
                                //获取id和对应相似度数据,最大的5个
                                for (int i = 0; i < m_matchResult.MatchAttributeResult.Count; i++)
                                {
                                    if (m_matchResult.MatchAttributeResult[i][0] == ID)
                                    {
                                        if (IDs.Count < 5)
                                        {
                                            //记录下与当前ID值匹配的第二数据集的id和相似度值
                                            IDs.Add(m_matchResult.MatchAttributeResult[i][1]);
                                            Values.Add(m_matchResult.MatchAttributeResult[i][2]);
                                        }
                                        else
                                        {
                                            double min = Values.Min();
                                            if (min < m_matchResult.MatchAttributeResult[i][2] * Weights[n])
                                            {
                                                int index = Values.IndexOf(min);
                                                IDs[index] = m_matchResult.MatchAttributeResult[i][1];
                                                Values[index] = m_matchResult.MatchAttributeResult[i][2] * Weights[n];
                                            }
                                        }
                                    }
                                }
                            }
                            break;
                        case 3:
                            //查询拓扑匹配(全部匹配，通常产生较多结果，因此只保留相似度最大的五项结果)
                            if (IDs.Count > 0)
                            {
                                for (int i = 0; i < m_matchResult.MatchTopologyResult.Count; i++)
                                {
                                    //当第二数据的id值已经包含在IDs数组中时，才获取相似度值
                                    if (m_matchResult.MatchTopologyResult[i][0] == ID && IDs.Contains(m_matchResult.MatchTopologyResult[i][1]))
                                    {
                                        //记录下当前匹配的相似度值
                                        int index = IDs.IndexOf(m_matchResult.MatchTopologyResult[i][1]);
                                        Values[index] += m_matchResult.MatchTopologyResult[i][2] * Weights[2];
                                    }
                                }
                            }
                            else
                            {
                                //获取id和对应相似度数据,最大的5个
                                for (int i = 0; i < m_matchResult.MatchTopologyResult.Count; i++)
                                {
                                    if (m_matchResult.MatchTopologyResult[i][0] == ID)
                                    {
                                        if (IDs.Count < 5)
                                        {
                                            //记录下与当前ID值匹配的第二数据集的id和相似度值
                                            IDs.Add(m_matchResult.MatchTopologyResult[i][1]);
                                            Values.Add(m_matchResult.MatchTopologyResult[i][2]);
                                        }
                                        else
                                        {
                                            double min = Values.Min();
                                            if (min < m_matchResult.MatchTopologyResult[i][2] * Weights[n])
                                            {
                                                int index = Values.IndexOf(min);
                                                IDs[index] = m_matchResult.MatchTopologyResult[i][1];
                                                Values[index] = m_matchResult.MatchTopologyResult[i][2] * Weights[n];
                                            }
                                        }
                                    }
                                }
                            }
                            break;
                        default:
                            break;
                    }
                }
                //获取相似度最大的值，并返回对应数据集2的ID
                int indexId = Values.IndexOf(Values.Max());
                if (indexId != -1)
                {
                    return IDs[indexId];
                }
                else
                {
                    //没有值，则返回异常
                    return -1.0;
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}
